//
//  AliyunOSSManager.m
//  SKinDiary
//
//  Created by pcyang on 16/7/13.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "AliyunOSSManager.h"
#import <AliyunOSSiOS/OSSService.h>
#import <AliyunOSSiOS/OSSCompat.h>
#import <UIKit/UIKit.h>

NSString * const AccessKey = @"qkREjtYFlBHTTwxD";
NSString * const SecretKey = @"VoMOWGTfejU1iaM05vEfpOw1WWwpae";
NSString * const endPoint = @"http://img-cn-hangzhou.aliyuncs.com";
NSString * const multipartUploadKey = @"multipartUploadObject";

OSSClient * client;
static dispatch_queue_t queue4demo;

@implementation AliyunOSSManager
+(AliyunOSSManager*)sharedInstance
{
    static AliyunOSSManager* sharedInstance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[AliyunOSSManager alloc] init];
    });
    
    return sharedInstance;
}

-(id)init
{
    self = [super init];
    if (self) {
        [OSSLog enableLog];
        
        
        [self initOSSClient];

    }
    
    return self;
}

- (void)initOSSClient {
    
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey
                                                                                                            secretKey:SecretKey];
    
    //    // 自实现签名，可以用本地签名也可以远程加签
    //    id<OSSCredentialProvider> credential1 = [[OSSCustomSignerCredentialProvider alloc] initWithImplementedSigner:^NSString *(NSString *contentToSign, NSError *__autoreleasing *error) {
    //        NSString *signature = [OSSUtil calBase64Sha1WithData:contentToSign withSecret:@"<your secret key>"];
    //        if (signature != nil) {
    //            *error = nil;
    //        } else {
    //            // construct error object
    //            *error = [NSError errorWithDomain:@"<your error domain>" code:OSSClientErrorCodeSignFailed userInfo:nil];
    //            return nil;
    //        }
    //        return [NSString stringWithFormat:@"OSS %@:%@", @"<your access key>", signature];
    //    }];
    //
    //    // Federation鉴权，建议通过访问远程业务服务器获取签名
    //    // 假设访问业务服务器的获取token服务时，返回的数据格式如下：
    //    // {"accessKeyId":"STS.iA645eTOXEqP3cg3VeHf",
    //    // "accessKeySecret":"rV3VQrpFQ4BsyHSAvi5NVLpPIVffDJv4LojUBZCf",
    //    // "expiration":"2015-11-03T09:52:59Z[;",
    //    // "federatedUser":"335450541522398178:alice-001",
    //    // "requestId":"C0E01B94-332E-4582-87F9-B857C807EE52",
    //    // "securityToken":"CAES7QIIARKAAZPlqaN9ILiQZPS+JDkS/GSZN45RLx4YS/p3OgaUC+oJl3XSlbJ7StKpQp1Q3KtZVCeAKAYY6HYSFOa6rU0bltFXAPyW+jvlijGKLezJs0AcIvP5a4ki6yHWovkbPYNnFSOhOmCGMmXKIkhrRSHMGYJRj8AIUvICAbDhzryeNHvUGhhTVFMuaUE2NDVlVE9YRXFQM2NnM1ZlSGYiEjMzNTQ1MDU0MTUyMjM5ODE3OCoJYWxpY2UtMDAxMOG/g7v6KToGUnNhTUQ1QloKATEaVQoFQWxsb3cSHwoMQWN0aW9uRXF1YWxzEgZBY3Rpb24aBwoFb3NzOioSKwoOUmVzb3VyY2VFcXVhbHMSCFJlc291cmNlGg8KDWFjczpvc3M6KjoqOipKEDEwNzI2MDc4NDc4NjM4ODhSAFoPQXNzdW1lZFJvbGVVc2VyYABqEjMzNTQ1MDU0MTUyMjM5ODE3OHIHeHljLTAwMQ=="}
    //    id<OSSCredentialProvider> credential2 = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
    //        NSURL * url = [NSURL URLWithString:@"http://localhost:8080/distribute-token.json"];
    //        NSURLRequest * request = [NSURLRequest requestWithURL:url];
    //        OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];
    //        NSURLSession * session = [NSURLSession sharedSession];
    //        NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
    //                                                    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    //                                                        if (error) {
    //                                                            [tcs setError:error];
    //                                                            return;
    //                                                        }
    //                                                        [tcs setResult:data];
    //                                                    }];
    //        [sessionTask resume];
    //        [tcs.task waitUntilFinished];
    //        if (tcs.task.error) {
    //            NSLog(@"get token error: %@", tcs.task.error);
    //            return nil;
    //        } else {
    //            NSDictionary * object = [NSJSONSerialization JSONObjectWithData:tcs.task.result
    //                                                                    options:kNilOptions
    //                                                                      error:nil];
    //            OSSFederationToken * token = [OSSFederationToken new];
    //            token.tAccessKey = [object objectForKey:@"accessKeyId"];
    //            token.tSecretKey = [object objectForKey:@"accessKeySecret"];
    //            token.tToken = [object objectForKey:@"securityToken"];
    //            token.expirationTimeInGMTFormat = [object objectForKey:@"expiration"];
    //            NSLog(@"get token: %@", token);
    //            return token;
    //        }
    //    }];
    
    
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    conf.maxRetryCount = 2;
    conf.timeoutIntervalForRequest = 30;
    conf.timeoutIntervalForResource = 24 * 60 * 60;
    
    client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:conf];
}

// 同步上传
- (void)uploadObjectSyncWithFileName:(NSString*)fileName image:(UIImage*)image  completion:(void (^)(id data, NSError *error))completion
{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    
    // required fields
    put.bucketName = @"jifurizhi";
    // put.objectKey = @"file1m";
    put.objectKey = fileName;
    
    // put.uploadingFileURL = [NSURL fileURLWithPath:[docDir stringByAppendingPathComponent:@"file1m"]];
    
   // UIImage* image = [UIImage imageNamed:@"map.png"];
    NSData *imgData = UIImagePNGRepresentation(image);
    
    put.uploadingData = imgData;
    
    // optional fields
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    put.contentType = @"application/x-png";
    put.contentMd5 = @"";
    put.contentEncoding = @"";
    put.contentDisposition = @"";
    
    OSSTask * putTask = [client putObject:put];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [putTask waitUntilFinished]; // 阻塞直到上传完成

        dispatch_async(dispatch_get_main_queue(), ^{
            if (!putTask.error) {
                OSSPutObjectResult * result = putTask.result;
                
                
             //   NSLog(@"upload object success!");
            } else {
               // NSLog(@"upload object failed, error: %@" , putTask.error);
            }
            
            if (completion) {
                OSSPutObjectResult * result = putTask.result;
                NSString* resultUrl = [NSString stringWithFormat:@"http://jifurizhi.img-cn-hangzhou.aliyuncs.com/%@",fileName];
                completion(resultUrl,putTask.error);
            }

        });
        
    });    
}
@end
